/**
 * token验证
 */

const NodeRSA = require('node-rsa');
const fs = require('fs');
const log = require('./log');


class RSAClass {

    constructor() {}

    // 生成 token 类
    creatToken() {
        fs.exists('./pem/common.pem', exis => {
            if (exis) {
                log.warn(' 公钥已存在！ ');
            } else {
                var key = new NodeRSA({b: 512});
                key.setOptions({encryptionScheme: 'pkcs1'});

                var privatePem = key.exportKey('pkcs1-private-pem');
                var publicPem = key.exportKey('pkcs1-common-pem');

                fs.writeFile('./pem/common.pem', publicPem, (err) => {
                    if (err) throw err;
                    console.log('公钥已保存！')
                });
                fs.writeFile('./pem/private.pem', privatePem, (err) => {
                    if (err) throw err;
                    console.log('私钥已保存！')
                })
            }
        });

    }

    encrypt(str) {
        return new Promise((resolve, reject) => {
            fs.readFile('./pem/private.pem', function (err, data) {
                if (err) {
                    reject('文件读取失败：' + err)
                } else {
                    var key = new NodeRSA(data);
                    let cipherText = key.encryptPrivate(str, 'base64');
                    resolve(cipherText);
                }
            });
        })
    }

    decrypt(tokey) {
        return new Promise((resolve, reject) => {
            fs.readFile('./pem/common.pem', function (err, data) {
                try {
                    var key = new NodeRSA(data);
                    let rawText = key.decryptPublic(tokey, 'utf8');
                    resolve(rawText);
                } catch (e) {
                    log.err('Token错误：' + e);
                    resolve(4011)
                }
            });
        });
    }

}

module.exports = RSAClass;